<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:sales:shopSalesPackage:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor
          v-model:value="model[field]"
          :bizKey="record.id"
          :bizType="'shopSalesPackage_' + field"
          :height="500"
          :disabled="true"
        />
      </template>
      <template #salesSelect>
        <ListSelect
          v-model:value="itemCodes"
          :labelValue="itemNames"
          selectType="basInvSelect-orderback-all"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template>
      <!-- 物料 -->
      <template #shopSalesPackagesList>
        <BasicTable
          @register="registerShopSalesPackagesTable"
          @row-click="handleShopSalesPackagesRowClick"
        >
          <template #toolbar>
            <a-popconfirm
              placement="bottom"
              title="是否确认取消分组？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleqxfz('0')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('取消分组') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesfz('0')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="icon-settings" /> {{ t('设置分组') }}
            </a-button>

            <a-popconfirm
              placement="bottom"
              title="是否确认批量取消发布？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleCancel('0')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('批量删除') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesedit('0')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="clarity:note-edit-line" /> {{ t('批量编辑') }}
            </a-button>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesAdd('0')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加物料') }}
            </a-button>
          </template>
        </BasicTable>

        <div v-if="record.showFooter">
          <div v-for="(item, key) in groupedMap" :key="key" style="padding: 10px 0">
            <!-- {{item[0].groupType}} {{item[0].groupName}} /  -->
            <div style="margin-bottom: 10px">
              <span style="font-size: 18px; font-weight: bold; margin-right: 20px">{{ key }}</span>
              （需选择总数：{{ item[0].groupQty }}）
              <span style="color: red">
                {{
                  item[0].groupType == '1'
                    ? '任选'
                    : item[0].groupType == '0'
                    ? '必选'
                    : item[0].groupType
                }}</span
              >

              <!-- <DictLabel v-if="item[0].groupType" :dictType="'btdm_package_group'" :dictValue="item[0].groupType"
                :defaultValue="item[0].groupType" /> -->
            </div>
            <a-checkbox-group v-model:value="item.value">
              <a-checkbox v-for="(item2, index2) in item" :key="item2.id" :value="item2.id"
                >{{ item2.basInv.cinvname }}（{{ item2.basInv.cinvcode }}）</a-checkbox
              >
            </a-checkbox-group>
          </div>
        </div>
      </template>

      <!-- 主产品 -->
      <template #shopSalesPackagesListzcp>
        <BasicTable
          @register="registerShopSalesPackagesTablezcp"
          @row-click="handleShopSalesPackagesRowClick"
        >
          <template #toolbar>
            <a-popconfirm
              placement="bottom"
              title="是否确认取消分组？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleqxfz('1')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('取消分组') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesfz('1')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="icon-settings" /> {{ t('设置分组') }}
            </a-button>

            <a-popconfirm
              placement="bottom"
              title="是否确认批量取消发布？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleCancel('1')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('批量删除') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesedit('1')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="clarity:note-edit-line" /> {{ t('批量编辑') }}
            </a-button>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesAdd('1')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加物料') }}
            </a-button>
          </template>
        </BasicTable>
        <div v-if="record.showFooter">
          <div v-for="(item, key) in groupedMapzcp" :key="key" style="padding: 10px 0">
            <!-- {{item[0].groupType}} {{item[0].groupName}} /  -->
            <div style="margin-bottom: 10px">
              <span style="font-size: 18px; font-weight: bold; margin-right: 20px">{{ key }}</span>
              （需选择总数：{{ item[0].groupQty }}）
              <span style="color: red">
                {{
                  item[0].groupType == '1'
                    ? '任选'
                    : item[0].groupType == '0'
                    ? '必选'
                    : item[0].groupType
                }}</span
              >

              <!-- <DictLabel v-if="item[0].groupType" :dictType="'btdm_package_group'" :dictValue="item[0].groupType"
                :defaultValue="item[0].groupType" /> -->
            </div>
            <a-checkbox-group v-model:value="item.value">
              <a-checkbox v-for="(item2, index2) in item" :key="item2.id" :value="item2.id"
                >{{ item2.basInv.cinvname }}（{{ item2.basInv.cinvcode }}）</a-checkbox
              >
            </a-checkbox-group>
          </div>
        </div>
      </template>

      <!-- 辅品 -->
      <template #shopSalesPackagesListfp>
        <BasicTable
          @register="registerShopSalesPackagesTablefp"
          @row-click="handleShopSalesPackagesRowClick"
        >
          <template #toolbar>
            <a-popconfirm
              placement="bottom"
              title="是否确认取消分组？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleqxfz('2')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('取消分组') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesfz('2')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="icon-settings" /> {{ t('设置分组') }}
            </a-button>

            <a-popconfirm
              placement="bottom"
              title="是否确认批量取消发布？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleCancel('2')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('批量删除') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesedit('2')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="clarity:note-edit-line" /> {{ t('批量编辑') }}
            </a-button>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesAdd('2')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加物料') }}
            </a-button>
          </template>
        </BasicTable>
        <div style="text-align: right; margin-right: 25px">
          总金额合计：{{ total ? total : 0 }}
        </div>

        <div v-if="record.showFooter">
          <div v-for="(item, key) in groupedMapfp" :key="key" style="padding: 10px 0">
            <!-- {{item[0].groupType}} {{item[0].groupName}} /  -->
            <div style="margin-bottom: 10px">
              <span style="font-size: 18px; font-weight: bold; margin-right: 20px">{{ key }}</span>
              （需选择总数：{{ item[0].groupQty }}）
              <span style="color: red">
                {{
                  item[0].groupType == '1'
                    ? '任选'
                    : item[0].groupType == '0'
                    ? '必选'
                    : item[0].groupType
                }}</span
              >

              <!-- <DictLabel v-if="item[0].groupType" :dictType="'btdm_package_group'" :dictValue="item[0].groupType"
                :defaultValue="item[0].groupType" /> -->
            </div>
            <a-checkbox-group v-model:value="item.value">
              <a-checkbox v-for="(item2, index2) in item" :key="item2.id" :value="item2.id"
                >{{ item2.basInv.cinvname }}（{{ item2.basInv.cinvcode }}）</a-checkbox
              >
            </a-checkbox-group>
          </div>
        </div>
      </template>

      <template #czpList>
        <BasicTable
          @register="registerShopSalesPackagesTableczp"
          @row-click="handleShopSalesPackagesRowClick"
        >
          <template #toolbar>
            <a-popconfirm
              placement="bottom"
              title="是否确认取消分组？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleqxfz('3')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('取消分组') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesfz('3')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="icon-settings" /> {{ t('设置分组') }}
            </a-button>

            <a-popconfirm
              placement="bottom"
              title="是否确认批量取消发布？"
              ok-text="是"
              cancel-text="否"
              @confirm="handleCancel('3')"
            >
              <a-button
                v-if="record.fbStatus != '1'"
                class="mt-2"
                v-auth="'shop:sales:shopSalesPackage:view'"
              >
                <Icon icon="simple-line-icons:close" /> {{ t('批量删除') }}
              </a-button>
            </a-popconfirm>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesedit('3')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="clarity:note-edit-line" /> {{ t('批量编辑') }}
            </a-button>
            <a-button
              v-if="record.fbStatus != '1'"
              class="mt-2"
              @click="handleShopSalesPackagesAdd('3')"
              v-auth="'shop:sales:shopSalesPackage:edit'"
            >
              <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加物料') }}
            </a-button>
          </template>
        </BasicTable>
        <div style="text-align: right; margin-right: 25px">
          总金额合计：{{ total ? total : 0 }}
        </div>

        <div v-if="record.showFooter">
          <div v-for="(item, key) in groupedMapczp" :key="key" style="padding: 10px 0">
            <!-- {{item[0].groupType}} {{item[0].groupName}} /  -->
            <div style="margin-bottom: 10px">
              <span style="font-size: 18px; font-weight: bold; margin-right: 20px">{{ key }}</span>
              （需选择总数：{{ item[0].groupQty }}）
              <span style="color: red">
                {{
                  item[0].groupType == '1'
                    ? '任选'
                    : item[0].groupType == '0'
                    ? '必选'
                    : item[0].groupType
                }}</span
              >

              <!-- <DictLabel v-if="item[0].groupType" :dictType="'btdm_package_group'" :dictValue="item[0].groupType"
                :defaultValue="item[0].groupType" /> -->
            </div>
            <a-checkbox-group v-model:value="item.value">
              <a-checkbox v-for="(item2, index2) in item" :key="item2.id" :value="item2.id"
                >{{ item2.basInv.cinvname }}（{{ item2.basInv.cinvcode }}）</a-checkbox
              >
            </a-checkbox-group>
          </div>
        </div>
      </template>
    </BasicForm>

    <addform @register="registeraddDrawer" @success="handleSuccess" />
    <fzform @register="registerfzDrawer" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopSalesShopSalesPackageForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed, reactive } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  // import { useDrawer } from '/@/components/Drawer';
  import { ListSelect } from '/@/components/ListSelect';
  import {
    ShopSalesPackage,
    shopSalesPackageSave,
    shopSalesPackageSalesForm,
    shopSalesPackageListData,
    shopSalesPackageSelPackage,
  } from '/@/api/shop/sales/shopSalesPackage';
  import {
    shopSalesPackagesListData,
    shopSalesPackagesBatchDelete,
  } from '/@/api/shop/sales/shopSalesPackages';
  import addform from './addform.vue';
  import fzform from './fzform.vue';
  import {
    shopSalesPackagesSaveGroup,
    shopSalesPackagesCancelGroup,
  } from '/@/api/shop/sales/shopSalesPackages';
  import { DictLabel } from '/@/components/Dict';
  import { WangEditor } from '/@/components/WangEditor';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.sales.shopSalesPackage');
  const { showMessage } = useMessage();
  const record = ref<ShopSalesPackage>({} as ShopSalesPackage);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增套餐包') : t('编辑套餐包'),
    value: t('套餐包'),
  }));

  const state = reactive<{
    selectedRowKeys: Key[];
  }>({
    selectedRowKeys: [], // Check here to configure the default column
  });

  const onSelectChange = (selectedRowKeys: Key[]) => {
    state.selectedRowKeys = selectedRowKeys;
  };

  const itemCodes = ref('');
  const itemNames = ref('');
  let listSelectRef = ref([]);
  let queryParams = ref({});
  const salesInvType = ref('');

  let total = ref(0);

  let groupedMap = ref({});
  let groupedMapzcp = ref({});
  let groupedMapfp = ref({});
  let groupedMapczp = ref({});

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('标题'),
      field: 'title',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
      required: true,
      dynamicDisabled: true,
      // colProps: { lg: 24, md: 24 },
    },
    {
      label: t('发布状态'),
      field: 'fbStatus',
      component: 'Select',
      componentProps: {
        dictType: 'shop_fb_status',
        allowClear: true,
      },
      dynamicDisabled: true,
    },
    {
      label: t('生效日期'),
      field: 'beginDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      // colProps: { lg: 8, md: 24 },
    },
    {
      label: t('失效日期'),
      field: 'endDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      // colProps: { lg: 8, md: 24 },
    },

    {
      label: t('存货'),
      field: 'salesSelect',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'salesSelect',
      show: false,
    },
    {
      label: t('套餐介绍'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      slot: 'remarks',
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('物料系列-物料'),
      field: 'Info',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'shopSalesPackagesList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'shopSalesPackagesList',
    },
    {
      label: t('物料系列-主产品'),
      field: 'Info',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'shopSalesPackagesListzcp',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'shopSalesPackagesListzcp',
    },
    {
      label: t('物料系列-辅品'),
      field: 'Info',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'shopSalesPackagesListfp',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'shopSalesPackagesListfp',
    },
    {
      label: t('物料系列-次主品'),
      field: 'Info',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'czpList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'czpList',
    },
  ];

  const tableColumns: BasicColumn[] = [
    {
      title: t('物料编码'),
      dataIndex: 'basInv.cinvcode',
      width: 130,
      align: 'left',
    },
    {
      title: t('物料名称'),
      dataIndex: 'basInv.cinvname',
      width: 130,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'basInv.unitName',
      width: 70,
      align: 'left',
    },
    {
      title: t('选择类型'),
      dataIndex: 'groupType',
      width: 70,
      align: 'center',
      dictType: 'btdm_package_group',
    },
    {
      title: t('需选择总数'),
      dataIndex: 'groupQty',
      width: 70,
      align: 'center',
    },
    {
      title: t('分组名称'),
      dataIndex: 'groupName',
      width: 130,
      align: 'left',
    },
    {
      title: t('分组标志'),
      dataIndex: 'groupId',
      width: 80,
      align: 'center',
      dictType: 'btdm_package_group_id',
    },
    {
      title: t('是否赠品'),
      dataIndex: 'bgift',
      width: 80,
      align: 'center',
      dictType: 'sys_yes_no',
    },
    {
      title: t('件数'),
      dataIndex: 'iqty',
      width: 80,
      align: 'center',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      width: 80,
      align: 'center',
    },
    {
      title: t('金额'),
      dataIndex: 'isum',
      width: 80,
      align: 'center',
    },
  ];

  const tableColumnszcp: BasicColumn[] = [
    {
      title: t('物料编码'),
      dataIndex: 'basInv.cinvcode',
      width: 130,
      align: 'left',
    },
    {
      title: t('物料名称'),
      dataIndex: 'basInv.cinvname',
      width: 130,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'basInv.unitName',
      width: 70,
      align: 'left',
    },
    {
      title: t('选择类型'),
      dataIndex: 'groupType',
      width: 70,
      align: 'center',
      dictType: 'btdm_package_group',
    },
    {
      title: t('需选择总数'),
      dataIndex: 'groupQty',
      width: 70,
      align: 'center',
    },
    {
      title: t('分组名称'),
      dataIndex: 'groupName',
      width: 130,
      align: 'left',
    },
    {
      title: t('分组标志'),
      dataIndex: 'groupId',
      width: 80,
      align: 'center',
      dictType: 'btdm_package_group_id',
    },
    {
      title: t('是否赠品'),
      dataIndex: 'bgift',
      width: 80,
      align: 'center',
      dictType: 'sys_yes_no',
    },
    {
      title: t('件数'),
      dataIndex: 'iqty',
      width: 80,
      align: 'center',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      width: 80,
      align: 'center',
    },
    {
      title: t('金额'),
      dataIndex: 'isum',
      width: 80,
      align: 'center',
    },
  ];

  const tableColumnsfp: BasicColumn[] = [
    {
      title: t('物料编码'),
      dataIndex: 'basInv.cinvcode',
      width: 130,
      align: 'left',
    },
    {
      title: t('物料名称'),
      dataIndex: 'basInv.cinvname',
      width: 130,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'basInv.unitName',
      width: 70,
      align: 'left',
    },
    {
      title: t('选择类型'),
      dataIndex: 'groupType',
      width: 70,
      align: 'center',
      dictType: 'btdm_package_group',
    },
    {
      title: t('需选择总数'),
      dataIndex: 'groupQty',
      width: 70,
      align: 'center',
    },
    {
      title: t('分组名称'),
      dataIndex: 'groupName',
      width: 130,
      align: 'left',
    },
    {
      title: t('分组标志'),
      dataIndex: 'groupId',
      width: 80,
      align: 'center',
      dictType: 'btdm_package_group_id',
    },

    {
      title: t('是否赠品'),
      dataIndex: 'bgift',
      width: 80,
      align: 'center',
      dictType: 'sys_yes_no',
    },
    {
      title: t('件数'),
      dataIndex: 'iqty',
      width: 80,
      align: 'center',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      width: 80,
      align: 'center',
    },
    {
      title: t('金额'),
      dataIndex: 'isum',
      width: 80,
      align: 'center',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerShopSalesPackagesTable, shopSalesPackagesTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleShopSalesPackagesDelete.bind(this, record),
    //       },
    //       auth: 'shop:sales:shopSalesPackage:edit',
    //     },
    //   ],
    // },
    api: shopSalesPackagesListData,
    beforeFetch: (params) => {
      params.invType = '0';
      params['parent.id'] = record.value.id;
      return params;
    },
    columns: tableColumns,
    rowKey: 'id',
    pagination: false,
    // bordered: true,
    // size: 'small',
    // inset: true,
    showTableSetting: false,
    maxHeight: 300,
    rowSelection: {
      type: 'checkbox',
    },
    immediate: false,
    showSummary: true,
    summaryFunc: handleSummary,
  });
  const [registerShopSalesPackagesTablezcp, shopSalesPackagesTablezcp] = useTable({
    api: shopSalesPackagesListData,
    beforeFetch: (params) => {
      params.invType = '1';
      params['parent.id'] = record.value.id;
      return params;
    },
    columns: tableColumns,
    rowKey: 'id',
    pagination: false,
    showTableSetting: false,
    maxHeight: 300,
    rowSelection: {
      type: 'checkbox',
    },
    immediate: false,
    showSummary: true,
    summaryFunc: handleSummary,
  });
  const [registerShopSalesPackagesTablefp, shopSalesPackagesTablefp] = useTable({
    api: shopSalesPackagesListData,
    beforeFetch: (params) => {
      params.invType = '2';
      params['parent.id'] = record.value.id;
      return params;
    },
    columns: tableColumns,
    rowKey: 'id',
    pagination: false,
    showTableSetting: false,
    maxHeight: 300,
    rowSelection: { type: 'checkbox' },
    immediate: false,
    showSummary: true,
    summaryFunc: handleSummary,
  });

  const [registerShopSalesPackagesTableczp, shopSalesPackagesTableczp] = useTable({
    api: shopSalesPackagesListData,
    beforeFetch: (params) => {
      params.invType = '3';
      params['parent.id'] = record.value.id;
      return params;
    },
    columns: tableColumns,
    rowKey: 'id',
    pagination: false,
    showTableSetting: false,
    maxHeight: 300,
    rowSelection: { type: 'checkbox' },
    immediate: false,
    showSummary: true,
    summaryFunc: handleSummary,
  });
// 



  const [registerTablefz, salesTablefz] = useTable({
    columns: tableColumnsfp,
    rowKey: 'id',
    pagination: false,
    showTableSetting: false,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleSummary(tableData: Recordable[]) {
    // const isum = tableData.reduce((prev, next) => {
    //   prev += next.isum ? next.isum : 0;
    //   return prev;
    // }, 0);

    return [
      {
        // _row: '合计',
        _index: '合计',
        isum: tableData[0].totalMoney,
      },
    ];
  }

  async function setShopSalesPackagesTableData(_res: Recordable) {
    // shopSalesPackagesTable.setColumns([
    //   {
    //     title: t('物料编码'),
    //     dataIndex: 'basInv.cinvcode',
    //     width: 130,
    //     align: 'left',
    //   },
    //   {
    //     title: t('物料名称'),
    //     dataIndex: 'basInv.cinvname',
    //     width: 130,
    //     align: 'left',
    //   },
    //   {
    //     title: t('规格型号'),
    //     dataIndex: 'basInv.cinvstd',
    //     width: 100,
    //     align: 'left',
    //   },
    //   {
    //     title: t('单位'),
    //     dataIndex: 'basInv.unitName',
    //     width: 70,
    //     align: 'left',
    //   },
    //   {
    //     title: t('是否赠品'),
    //     dataIndex: 'bgift',
    //     width: 80,
    //     align: 'center',
    //     dictType: 'sys_yes_no',
    //   },
    //   {
    //     title: t('数量'),
    //     dataIndex: 'iqty',
    //     width: 80,
    //     align: 'center',
    //   },
    //   {
    //     title: t('单价'),
    //     dataIndex: 'iprice',
    //     width: 80,
    //     align: 'center',
    //   },
    //   {
    //     title: t('金额'),
    //     dataIndex: 'isum',
    //     width: 80,
    //     align: 'center',
    //   },
    //   // {
    //   //   title: t('选择类型'),
    //   //   dataIndex: 'groupType',
    //   //   width: 130,
    //   //   align: 'center',
    //   //   dictType: 'btdm_package_group',
    //   //   editRow: true,
    //   //   editComponent: 'Select',
    //   //   editComponentProps: {
    //   //     dictType: 'btdm_package_group',
    //   //     allowClear: true,
    //   //   },
    //   //   editRule: false,
    //   // },
    //   // {
    //   //   title: t('分组标志'),
    //   //   dataIndex: 'groupId',
    //   //   width: 130,
    //   //   align: 'center',
    //   //   dictType: 'btdm_package_group_id',
    //   //   editRow: true,
    //   //   editComponent: 'Select',
    //   //   editComponentProps: {
    //   //     dictType: 'btdm_package_group_id',
    //   //     allowClear: true,
    //   //   },
    //   //   editRule: false,
    //   // },
    //   // {
    //   //   title: t('分组名称'),
    //   //   dataIndex: 'groupName',
    //   //   width: 130,
    //   //   align: 'left',
    //   //   editRow: true,
    //   //   editComponent: 'Input',
    //   //   editComponentProps: {
    //   //     maxlength: 200,
    //   //   },
    //   //   editRule: false,
    //   // },
    //   // {
    //   //   title: t('选择数量'),
    //   //   dataIndex: 'groupQty',
    //   //   width: 130,
    //   //   align: 'center',
    //   //   editRow: true,
    //   //   editComponent: 'Input',
    //   //   editComponentProps: {
    //   //     maxlength: 8,
    //   //   },
    //   //   editRule: false,
    //   // },

    // ]);
    shopSalesPackagesTable.setTableData(record.value.wlList || []);
    shopSalesPackagesTablezcp.setTableData(record.value.mainList || []);
    shopSalesPackagesTablefp.setTableData(record.value.fpList || []);
    shopSalesPackagesTableczp.setTableData(record.value.czpList || []);
  }

  function handleShopSalesPackagesRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handSelect(selectData) {
    console.log(salesInvType.value, '6666');
    console.log(record.value.salesInvType, '111');
    if (salesInvType.value == '0') {
      let arr = [];
      selectData.forEach((item) => {
        let flag = true;
        shopSalesPackagesTable.getDataSource().forEach((item2) => {
          if (item.cinvcode == item2.basInv.cinvcode) {
            flag = false;
          }
        });
        if (flag) {
          arr.push(item);
        }
      });
      let newarr = arr.map((item) => {
        return item.cinvcode;
      });
      openaddDrawer(true, {
        wlType: salesInvType.value,
        selInvs: newarr.join(','),
        id: record.value.id,
        isNewRecord: true,
      });
    } else if (salesInvType.value == '1') {
      // console.log(shopSalesPackagesTablezcp.getDataSource());
      let arr = [];
      selectData.forEach((item) => {
        let flag = true;
        shopSalesPackagesTablezcp.getDataSource().forEach((item2) => {
          if (item.cinvcode == item2.basInv.cinvcode) {
            flag = false;
          }
        });
        if (flag) {
          arr.push(item);
        }
      });
      let newarr = arr.map((item) => {
        return item.cinvcode;
      });
      openaddDrawer(true, {
        wlType: salesInvType.value,
        selInvs: newarr.join(','),
        id: record.value.id,
        isNewRecord: true,
      });
    } else if (salesInvType.value == '2') {
      let arr = [];
      selectData.forEach((item) => {
        let flag = true;
        shopSalesPackagesTablefp.getDataSource().forEach((item2) => {
          if (item.cinvcode == item2.basInv.cinvcode) {
            flag = false;
          }
        });
        if (flag) {
          arr.push(item);
        }
      });
      let newarr = arr.map((item) => {
        return item.cinvcode;
      });
      openaddDrawer(true, {
        wlType: salesInvType.value,
        selInvs: newarr.join(','),
        id: record.value.id,
        isNewRecord: true,
      });
    } else if (salesInvType.value == '3') {
      let arr = [];
      selectData.forEach((item) => {
        let flag = true;
        shopSalesPackagesTableczp.getDataSource().forEach((item2) => {
          if (item.cinvcode == item2.basInv.cinvcode) {
            flag = false;
          }
        });
        if (flag) {
          arr.push(item);
        }
      });
      let newarr = arr.map((item) => {
        return item.cinvcode;
      });
      openaddDrawer(true, {
        wlType: salesInvType.value,
        selInvs: newarr.join(','),
        id: record.value.id,
        isNewRecord: true,
      });
    }
  }

  async function handleCancel(type) {
    if (type == '0') {
      if (shopSalesPackagesTable.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTable.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });

        const res = await shopSalesPackagesBatchDelete({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTable.reload();
        // openaddDrawer(true, {selIds:selIds.value})
      } else {
        showMessage('请先选择一行数据！');
      }
    } else if (type == '1') {
      if (shopSalesPackagesTablezcp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablezcp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesBatchDelete({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTablezcp.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    } else if (type == '2') {
      if (shopSalesPackagesTablefp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablefp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesBatchDelete({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTablefp.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    } else if (type == '3') {
      if (shopSalesPackagesTableczp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTableczp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesBatchDelete({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTableczp.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    }
  }

  function handleShopSalesPackagesfz(wlType) {
    if (wlType == '0') {
      if (shopSalesPackagesTable.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTable.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openfzDrawer(true, { selIds: selIds.value, wlType, pid: record.value.id });
      } else {
        showMessage('请先选择一行数据！');
      }
    }

    if (wlType == '1') {
      if (shopSalesPackagesTablezcp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablezcp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openfzDrawer(true, { selIds: selIds.value, wlType, pid: record.value.id });
      } else {
        showMessage('请先选择一行数据！');
      }
    }
    if (wlType == '2') {
      if (shopSalesPackagesTablefp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablefp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openfzDrawer(true, { selIds: selIds.value, wlType, pid: record.value.id });
      } else {
        showMessage('请先选择一行数据！');
      }
    }
    if (wlType == '3') {
      if (shopSalesPackagesTableczp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTableczp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openfzDrawer(true, { selIds: selIds.value, wlType, pid: record.value.id });
      } else {
        showMessage('请先选择一行数据！');
      }
    }
  }
  async function handleqxfz(wlType) {
    if (wlType == '0') {
      if (shopSalesPackagesTable.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTable.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesCancelGroup({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTable.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    }

    if (wlType == '1') {
      if (shopSalesPackagesTablezcp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablezcp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesCancelGroup({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTablezcp.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    }

    if (wlType == '2') {
      if (shopSalesPackagesTablefp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablefp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesCancelGroup({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTablefp.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    }

    if (wlType == '3') {
      if (shopSalesPackagesTableczp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTableczp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        const res = await shopSalesPackagesCancelGroup({ selIds: selIds.value });
        showMessage(res.message);
        shopSalesPackagesTableczp.reload();
      } else {
        showMessage('请先选择一行数据！');
      }
    }
  }

  function handleShopSalesPackagesedit(type) {
    if (type == '0') {
      if (shopSalesPackagesTable.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTable.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openaddDrawer(true, {
          wlType: type,
          selIds: selIds.value,
          id: record.value.id,
          isNewRecord: false,
        });
      } else {
        showMessage('请先选择一行数据！');
      }
    } else if (type == '1') {
      if (shopSalesPackagesTablezcp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablezcp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openaddDrawer(true, {
          wlType: type,
          selIds: selIds.value,
          id: record.value.id,
          isNewRecord: false,
        });
      } else {
        showMessage('请先选择一行数据！');
      }
    } else if (type == '2') {
      if (shopSalesPackagesTablefp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTablefp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openaddDrawer(true, {
          wlType: type,
          selIds: selIds.value,
          id: record.value.id,
          isNewRecord: false,
        });
      } else {
        showMessage('请先选择一行数据！');
      }
    } else if (type == '3') {
      if (shopSalesPackagesTableczp.getSelectRows().length) {
        var selIds = ref('');
        shopSalesPackagesTableczp.getSelectRows().forEach((item) => {
          selIds.value += item.id + ',';
        });
        openaddDrawer(true, {
          wlType: type,
          selIds: selIds.value,
          id: record.value.id,
          isNewRecord: false,
        });
      } else {
        showMessage('请先选择一行数据！');
      }
    }
  }
  async function totalnum() {
    let res = await shopSalesPackagesListData({ 'parent.id': record.value.id });
    total.value = res.length ? res[0].totalMoney : 0;
  }

  function handleSuccess(type) {
    console.log(type);
    if (type == '0') {
      shopSalesPackagesTable.reload();
    }
    if (type == '1') {
      shopSalesPackagesTablezcp.reload();
    }
    if (type == '2') {
      shopSalesPackagesTablefp.reload();
    }
    if (type == '3') {
      shopSalesPackagesTableczp.reload();
    }
    totalnum();
  }

  function handleShopSalesPackagesAdd(type) {
    // shopSalesPackagesTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    record.value.salesInvType = type;
    salesInvType.value = type;
    console.log(type, 'type===');
    console.log(salesInvType.value, 'salesInvType.value===2222222');
    listSelectRef.value = [];
    document.getElementById('form_item_salesSelect')?.click();
    console.log(salesInvType.value, 'salesInvType.value===33333333');
  }

  function handleShopSalesPackagesDelete(record: Recordable) {
    shopSalesPackagesTable.deleteTableDataRecord(record);
  }

  async function getShopSalesPackagesList() {
    let shopSalesPackagesListValid = true;
    let shopSalesPackagesList: Recordable[] = [];
    for (const record of shopSalesPackagesTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        shopSalesPackagesListValid = false;
      }
      shopSalesPackagesList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of shopSalesPackagesTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      shopSalesPackagesList.push({
        ...record,
        status: '1',
      });
    }
    if (!shopSalesPackagesListValid) {
      throw { errorFields: [{ name: ['shopSalesPackagesList'] }] };
    }
    return shopSalesPackagesList;
  }

  const [registerfzDrawer, { openDrawer: openfzDrawer }] = useDrawer();
  const [registeraddDrawer, { openDrawer: openaddDrawer }] = useDrawer();
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await shopSalesPackageSalesForm(data);
    groupedMap.value = res.resMap.wlMap || {};
    groupedMapzcp.value = res.resMap.mainMap || {};
    groupedMapfp.value = res.resMap.fpMap || {};
    groupedMapczp.value = res.resMap.czpMap || {};
    for (const key in groupedMap.value) {
      groupedMap.value[key].forEach((item) => {
        item.key = item.id;
      });
    }
    for (const key in groupedMapzcp.value) {
      groupedMapzcp.value[key].forEach((item) => {
        item.key = item.id;
      });
    }
    for (const key in groupedMapfp.value) {
      groupedMapfp.value[key].forEach((item) => {
        item.key = item.id;
      });
    }
    for (const key in groupedMapczp.value) {
      groupedMapczp.value[key].forEach((item) => {
        item.key = item.id;
      });
    }

    record.value = (res.shopSalesPackage || {}) as ShopSalesPackage;
    record.value.__t = new Date().getTime();
    setDrawerProps({ showOkBtn: !data.showFooter ? false : true });
    console.log(data, 'record.value==');
    if (data.showFooter) {
      shopSalesPackagesTable.setProps({
        rowSelection: false,
      });
      shopSalesPackagesTablezcp.setProps({
        rowSelection: false,
      });
      shopSalesPackagesTablefp.setProps({
        rowSelection: false,
      });
      shopSalesPackagesTableczp.setProps({
        rowSelection: false,
      });
    }

    shopSalesPackagesTable.reload();
    shopSalesPackagesTablezcp.reload();
    shopSalesPackagesTablefp.reload();
    shopSalesPackagesTableczp.reload();
    totalnum();
    setFieldsValue(record.value);
    record.value.showFooter = data.showFooter ? true : false;
    // setShopSalesPackagesTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    // console.log( groupedMap.value,' groupedMap.value==');
    // if(groupedMap.value[key].value){
    //   groupedMap.value[key].value.forEach(item=>{
    //     arr.push(item)
    //   })
    // }
    // let flag = true
    // setTimeout(closeDrawer);
    // emit('success', res.list);
    // if(!flag){
    //   showMessage(t('请先选择分组，且选择不能大于需选择总数！'));
    //   return false;
    // }
    try {
      setDrawerProps({ confirmLoading: true });
      let wlList = [];
      let mainList = [];
      let fpList = [];
      let czpList = [];
      for (const key in groupedMap.value) {
        wlList.push({
          groupId: groupedMap.value[key][0].groupId,
          selIds: groupedMap.value[key].value ? groupedMap.value[key].value.join(',') : '',
        });
      }
      for (const key in groupedMapzcp.value) {
        mainList.push({
          groupId: groupedMapzcp.value[key][0].groupId,
          selIds: groupedMapzcp.value[key].value ? groupedMapzcp.value[key].value.join(',') : '',
        });
      }
      for (const key in groupedMapfp.value) {
        fpList.push({
          groupId: groupedMapfp.value[key][0].groupId,
          selIds: groupedMapfp.value[key].value ? groupedMapfp.value[key].value.join(',') : '',
        });
      }

      for (const key in groupedMapczp.value) {
        czpList.push({
          groupId: groupedMapczp.value[key][0].groupId,
          selIds: groupedMapczp.value[key].value ? groupedMapczp.value[key].value.join(',') : '',
        });
      }

      const params: any = {
        id: record.value.id,
        cusCode: record.value.cusCode,
        fpList,
        wlList,
        mainList,
        czpList,
      };
      let res = await shopSalesPackageSelPackage(params);
      // showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', res);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
